package q160_getIntersectionNode;

import CommonClass.Common.ListNode;

public class Solution_1 {
    /**
     * 单纯的先把AB两个链表的长度算出来，然后让长的先走一段
     * 直到两者长度相等开始同时next，直到相等就是相交点
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int m = 0, n = 0;
        ListNode tailA = headA;
        while (tailA != null) {
            tailA = tailA.next;
            m++;
        }

        ListNode tailB = headB;
        while (tailB != null) {
            tailB = tailB.next;
            n++;
        }
        tailA = headA;
        tailB = headB;
        if(m >= n){
            while(m > n){
                tailA = tailA.next;
                m--;
            }
            while (tailA != tailB && tailA != null) {
                tailA = tailA.next;
                tailB = tailB.next;
            }
            return tailA == null ? null : tailA;
        }else {
            while(m < n){
                tailB = tailB.next;
                n--;
            }
            while (tailA != tailB && tailA != null) {
                tailA = tailA.next;
                tailB = tailB.next;
            }
            return tailA == null ? null : tailA;
        }
    }
}
